package com.sun.common;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sun.entity.Log;
import com.sun.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;


/**
 * @Project: hospitalDrugInformationManagement
 * @Author: 86178
 * @Date: 2023/2/8 12:36
 * @FileName: Aop
 * @Description: ""
 */
@Aspect
@Component
@Slf4j
public class LoginLogAspect {

    @Autowired
    private LogService loginLogService;

    @Pointcut("execution(public * com.sun.controller.UserController.login*(..))")
    public void logPoinCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(public * com.sun.controller.*.*(..))")
    public void operExceptionLogPoinCut() {
    }

    /**
     * 后置通知，保存登录成功 日志
     */
    @AfterReturning(pointcut = "logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {

        try {
            // 获取目标方法所在的类的 Class 对象
            Class<?> clazz = joinPoint.getTarget().getClass();
            // 获取目标方法所在类中声明的所有成员变量
            Field[] fields = clazz.getDeclaredFields();
            // 遍历成员变量数组，查找目标方法中定义的变量
            for (Field field : fields) {
                if ("loginLog".equals(field.getName()) && field.getType().equals(Log.class)) {
                    // 找到目标方法中定义的变量，使用反射获取变量的值
                    field.setAccessible(true);
                    Log loginLog = (Log) field.get(joinPoint.getTarget());
                    loginLog.setId(IdWorker.getId());
                    loginLogService.save(loginLog);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//
//    /**
//     * 异常通知，保存登录失败 日志
//     *
//     */
//    @AfterThrowing(throwing = "e", pointcut = "logPoinCut()")
//    public void save(JoinPoint joinPoint, Exception e) {
//
//        HttpServletRequest request = HttpContextUtils.getRequest();
//        LogLogin logLogin = new LogLogin();
//
//        LoginLog annotation = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(LoginLog.class);
//
//        String paramName = annotation.param();
//        LoginDto loginDto = (LoginDto) AopUtils.getParamValue(joinPoint, paramName);
//        logLogin.setUsername(loginDto.getUsername());
//        logLogin.setIp(IPUtils.getIpAddr(request));
//        logLogin.setType(HttpContextUtils.getRequestFrom());
//        logLogin.setStatus(-1);
//        if (e instanceof WtaoException) {
//            logLogin.setReason(((WtaoException) e).getMsg());
//        } else {
//            logLogin.setReason("未知原因");
//        }
//        iLogLoginService.save(logLogin);
//    }

}
